<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate && baTable.form.operate !== 'origin'"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="设备型号" prop="equipmentName">
            <el-input
              class="filterInput"
              v-model="filterText"
              placeholder="关键词过滤"
            />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-tree
                ref="treeRef"
                class="filter-tree"
                :data="state.modelOptions"
                :props="{ label: 'modelCode', value: 'id' }"
                node-key="modelCode"
                show-checkbox
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.equipmentType]
                    : []
                "
                :filter-node-method="filterNode"
                @check="rightClick"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="设备编号" prop="equipmentCode">
            <el-input
              v-model="baTable.form.items!.equipmentCode"
              placeholder="请录入设备唯一编号"
            />
          </el-form-item>
          <el-form-item label="设备名称" prop="equipmentName">
            <el-input
              v-model="baTable.form.items!.equipmentName"
              placeholder="请选择设备型号"
              disabled
            />
          </el-form-item>
          <el-form-item label="网关绑定" prop="gatewaycode">
            {{ baTable.form.items!.gatewaycode }}
            <el-button
              v-if="baTable.form.operate === 'edit' && !state.bank"
              type="primary"
              style="margin-left: 10px"
              @click="unbind"
              >解绑</el-button
            >
            <el-input
              v-else
              v-model="filterTextIOT"
              placeholder="输入网关编号进行过滤"
              style="background: whitesmoke"
            />
            <el-scrollbar
              v-else
              ref="verticalMenusIOTRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-tree
                ref="treeRef3"
                class="filter-tree"
                :data="state.iotList"
                :props="{ label: 'code', value: 'code', disabled: 'bank' }"
                node-key="code"
                show-checkbox
                default-expand-all
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.gatewaycode]
                    : []
                "
                :filter-node-method="filterNodeIOT"
                @check="iotClick"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <span style="margin-left: 18px; color: yellowgreen">{{
                      !data.bank ? "未绑定" : "已绑定"
                    }}</span>
                  </span>
                </template>
              </el-tree>
            </el-scrollbar>
          </el-form-item>
          <FormItem
            label="设备激活状态"
            v-model="baTable.form.items!.state"
            type="radio"
            :data="{
              content: { 0: '离线', 1: '在线', 2: '未激活' },
              childrenAttr: { border: true },
            }"
          />
          <!-- <el-form-item label="设备种类" prop="process">
            <el-select
              v-model="baTable.form.items!.process"
              @change="processChange"
              clearable
            >
              <el-option
                v-for="item in state.gasHandleOptions"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item> -->

          <!-- <el-form-item label="处理风量" prop="volume">
            <el-input
              v-model="baTable.form.items!.volume"
              placeholder="请输入产品处理风量"
            ></el-input>
          </el-form-item>
          <el-form-item label="碳板数量" prop="plates">
            <el-input
              v-model="baTable.form.items!.plates"
              placeholder="请输入产品碳板数量"
            ></el-input>
          </el-form-item>
          <el-form-item label="生产商家" prop="producers">
            <el-input
              v-model="baTable.form.items!.producers"
              placeholder="请输入产品生产商家"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="额定功率(kw)" prop="power">
            <el-input
              v-model="baTable.form.items!.power"
              placeholder="请输入额定功率"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="user">
            <el-input
              v-model="baTable.form.items!.user"
              placeholder="维护人员信息"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="userPhone">
            <el-input
              v-model="baTable.form.items!.userPhone"
              placeholder="维护人员联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item label="心跳时长(ms)" prop="hearttime">
            <el-input
              v-model="baTable.form.items!.hearttime"
              placeholder="请输入心跳时长"
            ></el-input>
          </el-form-item>
          <el-form-item label="说明" prop="describe">
            <el-input
              v-model="baTable.form.items!.describe"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="产品说明"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "add" ? "保存并添加下一项" : "保存" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type { TableRow } from "@/utils/baTable"; //表格列行类型
import {
  reactive,
  ref,
  inject,
  onMounted,
  computed,
  watch,
  nextTick,
} from "vue";
import { ElButton } from "element-plus";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormRules, ElTree } from "element-plus";
import { ElNotification } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { getRegionName, changeBankToNumber } from "@/utils/common";
import { getPointByAddress } from "vue-baidu-map-3x"; //baidu-map组件red
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useAccessPoint } from "@/store/backend/AccessPointM/accessPoint";

type Option = {
  id: number;
  label: string;
  children: Option[];
};

//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const model = inject("model") as any;
const formRef = ref<InstanceType<typeof ElForm>>();
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeRef2 = ref<InstanceType<typeof ElTree>>();
const treeRef3 = ref<InstanceType<typeof ElTree>>();
const business = useBusiness();
const config = useConfig();
const dictionary = useDictionary();
const accessPoint = useAccessPoint();

const state: {
  deptOptions: Option[];
  location: string;
  menus: string[];
  companyOptions: anyObj[];
  regionOptions: anyObj[];
  gasHandleOptions: anyObj[];
  iotList: anyObj[];
  modelOptions: anyObj[];
  bank: boolean;
} = reactive({
  deptOptions: [], //部门列表
  location: "", //详细地址
  menus: [], //已选中的区域
  companyOptions: [], //企业列表
  regionOptions: [], //区域列表
  gasHandleOptions: [], //废气处理工艺列表 字典项
  iotList: [], //废气处理工艺列表 字典项
  modelOptions: [], //设备类型列表
  bank: false,
});
const processChange = (val: any) => {
  console.log(baTable.form.items!.process);
};
const filterText = ref(""); //设备型号关键词过滤
const filterTextIOT = ref(""); //网关
const filterNode = (value: string, data: any) => {
  console.log(value, data);

  if (!value) return true;
  return data.modelCode.includes(value);
};
//网关
const filterNodeIOT = (value: string, data: any) => {
  console.log("网关", value, data);
  if (!value) return true;
  return data.code.includes(value);
};

const getCheckeds = () => {
  return treeRef
    .value!.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};

const rules = reactive<FormRules>({
  equipmentCode: [
    { required: true, message: "设备编号不能为空", trigger: "blur" },
  ],
  equipmentType: [
    { required: true, message: "设备类型不能为空", trigger: "blur" },
  ],
  equipmentName: [
    { required: true, message: "设备名称不能为空", trigger: "blur" },
  ],
  addr: [{ required: true, message: "坐标需要进行转换" }],
  pressureValue: [
    { required: true, message: "激活设备压力初始值不能为空", trigger: "blur" },
  ],
  criticalValue: [
    { required: true, message: "激活设备压力临界值不能为空", trigger: "blur" },
  ],
  lifeValue: [
    {
      required: true,
      message: "激活设备使用寿命长度不能为空",
      trigger: "blur",
    },
  ],
  hearttime: [
    {
      required: true,
      message: "判断用户状态时间不能为空",
      trigger: "blur",
    },
  ],
  user: [
    {
      required: true,
      message: "活性炭维护人员信息不能为空",
      trigger: "blur",
    },
  ],
  volume: [
    {
      required: true,
      message: "处理风量信息不能为空",
      trigger: "blur",
    },
  ],
  plates: [
    {
      required: true,
      message: "碳板数量信息不能为空",
      trigger: "blur",
    },
  ],
  producers: [
    {
      required: true,
      message: "生产商家信息不能为空",
      trigger: "blur",
    },
  ],
  userPhone: [
    {
      required: true,
      message: "联系方式",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("手机号格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  // gatewaycode: [
  //   {
  //     required: true,
  //     message: "网关绑定",
  //     trigger: "trigger",
  //   },
  // ],
});

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});
//地址转换为坐标 北京市海淀区上地十街10号
const pointAndAddress = () => {
  getPointByAddress(
    {
      address: baTable.form.items!.addr,
    },
    ["wZcU7ugfOpZLuuRTAvNPn3Y36rpFxp1Q"]
  )
    .then((res) => {
      let { location, formatted_address } = res as any;
      baTable.form.items!.coordinate = JSON.stringify(location);
    })
    .catch((err: any) => {
      console.log(err);
      ElNotification({
        type: "warning",
        message: err + ",请检查并填写正确企业地址",
      });
      baTable.form.items!.addr = "";
      baTable.form.items!.coordinate = "";
      baTable.form.items!.institution = 0;
    });
};
// 选择设备型号
const rightClick = (MouseEvent: any, object: any, Node: any, element: any) => {
  console.log("型号选择的数据", MouseEvent, object, Node, element);
  if (object.checkedKeys.length) {
    baTable.form.items!.equipmentName = MouseEvent.modelName;
    baTable.form.items!.equipmentType = MouseEvent.modelCode;
  } else {
    baTable.form.items!.equipmentName = "";
    baTable.form.items!.equipmentType = "";
  }
};

const iotClick = (MouseEvent: any, object: any, Node: any, element: any) => {
  console.log("网关选择的数据", MouseEvent, object, Node, element);
  if (object.checkedKeys.length) {
    if (object.checkedKeys.length > 1) {
      ElNotification({
        type: "warning",
        message: "只能选择一个网关进行绑定",
      });
      return;
    }
    baTable.form.items!.gatewaycode = MouseEvent.code; //网关编号
    baTable.form.items!.cardnumber = MouseEvent.cardNumber; //流量卡号
  } else {
    console.log("取消绑定网关", baTable.form.items);
    baTable.form.items!.gatewaycode = ""; //网关编号为空
    baTable.form.items!.cardnumber = ""; //流量卡号为空
  }
};

//解绑
const unbind = () => {
  accessPoint.unbind(baTable.form.items.gatewaycode).then((res: any) => {
    state.bank = true;
    nextTick(() => {
      accessPoint.getIOTList({}).then((res: any) => {
        console.log("网关列表篇", res);
        state.iotList = changeBankToNumber(res.rows);
      });
    });
  });
};

onMounted(() => {
  // if (baTable.form.operate !== "edit") {
  //   accessPoint.getIOTList({ bank: "0" }).then((res: any) => {
  //     console.log("网关列表篇", res);
  //     state.iotList = changeBankToNumber(res.rows);
  //   });
  // } else {
  //   accessPoint.getIOTList({}).then((res: any) => {
  //     console.log("网关列表篇", res);
  //     state.iotList = changeBankToNumber(res.rows);
  //   });
  // }
  //获取设备类型列表
  model.getList({ pageSize: 1000 }).then((res: any) => {
    state.modelOptions = res.rows;
    console.log("获取设备类型列表", res);
  });
});
// defineExpose({
//   getCheckeds,
// });
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
watch(filterTextIOT, (val) => {
  treeRef3.value!.filter(val);
});
</script>
<style lang="scss" scoped>
.filter-tree {
  height: 200px;
}
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
